use async_tungstenite::{ async_std::connect_async, tungstenite::Message};
use axum::Json;
use futures_util::{SinkExt, StreamExt};
use serde_json::{json, Value};
use crate::{code, utils::host_ws};
// 服务器连接 websocket
pub async fn send(url:&str, msg:&str) -> Result<Json<Value>, Json<Value>> {
    let url = host_ws::ws_host_url(url);
    if let Ok(f) = connect_async(&url).await {
        let (mut ws_stream, _) = f;

        if ws_stream.send(Message::text(msg)).await.is_err() {
            code::err("send error")
        }else{
            if let Some(s) = ws_stream.next().await {
                match s {
                    Ok(m) => code::data(json!(m.to_string())),
                    Err(e) => code::sys(e.to_string())
                }
            }else{
                code::err("消息不存在")
            }
        }
    }else{
        code::err(format!("{} 连接失败", &url))
    }
}